package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 对于新增员工时，唯一索引字段重复，向前端回复
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //对于名字，是唯一索引，不能重复
        String message = ex.getMessage();//获取异常信息
        //java.sql.SQLIntegrityConstraintViolationException:
        //Duplicate entry 'huqi' for key 'employee.idx_username'
        if(message.contains("Duplicate entry")){
            String[] split = message.split(" ");//利用空格将字符串分开
            String username = split[2];//第三个字符
            //String mag = username+"已存在！";
            String mag = username+ MessageConstant.ALREADY_EXISTS;
            return Result.error(mag);
        }
        //return Result.error("未知错误！");
        return Result.error(MessageConstant.UNKNOWN_ERROR);
    }

}
